/**
 * 
 */
package com.bolbachchan.blog.controller.common;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.bolbachchan.blog.form.common.HomeFormObj;
import com.bolbachchan.blog.hibernate.domain.Posts;
import com.bolbachchan.blog.hibernate.domain.UserDetails;
import com.bolbachchan.blog.service.posts.UserPostsService;

/**
 * @author Chaitanya
 * 
 */
@Controller
public class HomeController extends DefaultController<HomeFormObj> {

    @Autowired
    private UserPostsService userPostsService;

    @RequestMapping(value = HOME_PAGE_VIEW, method = RequestMethod.GET)
    public String homePage(Model model, @ModelAttribute("fbb") HomeFormObj fbb) {
	fbb.setUserDetails(getUser());

	updateFbb(fbb);

	model.addAttribute(FBB, fbb);
	return HOME_PAGE_VIEW;
    }

    /**
     * @param fbb
     */
    private void updateFbb(HomeFormObj fbb) {
	UserDetails userDetails = fbb.getUserDetails();

	List<Posts> postsList = (List<Posts>) userPostsService.getPostsByUserId(userDetails.getObjId());
	Set<Posts> postsSet = new HashSet<Posts>();
	postsSet.addAll(postsList);
	userDetails.setPosts(postsSet);
    }

    /**
     * @return
     */
    @RequestMapping(value = ERROR_PAGE_VIEW, method = RequestMethod.GET)
    public String errorPage() {
	return COMMON_ERROR_VIEW;
    }
}
